#if UNITY_WEBGL

using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;

namespace ZhiSe.Editor
{
    public class SeegWebGLBuild
    {
        public static void AfterBuildTemplate(JObject cfg)
        {
            var indexPath = Path.Combine(SeegBuild.OutputPath, "index.html");
            if (!File.Exists(indexPath))
            {
                Debug.LogError("[SEEG] index.html 不存在，无法处理 WebGL 全局 unityInstance。");
                return;
            }
            var lines = File.ReadAllLines(indexPath).ToList();
            // 直接用字符串包含判断，兼容所有缩进
            for (var i = 0; i < lines.Count; i++)
            {
                if (lines[i].Contains("script.onload"))
                {
                    // 查找下一行
                    if (!lines[i + 1].Contains("window.zs"))
                    {
                        lines.Insert(i + 1, "window.zs = window.zs || {}; window.zs.gameConfig = " + cfg.ToString(Formatting.None));
                    }
                    else
                    {
                        lines[i + 1] = "window.zs = window.zs || {}; window.zs.gameConfig = " + cfg.ToString(Formatting.None);
                    }
                    continue;
                }

                if (!lines[i].Contains("then((unityInstance)"))
                {
                    continue;
                }
                // 查找下一行
                if (!lines[i + 1].Contains("window.unityInstance"))
                {
                    lines.Insert(i + 1, "window.unityInstance = unityInstance;");
                }
                break;
            }
            File.WriteAllLines(indexPath, lines);
            Debug.Log("[SEEG] 已将 unityInstance 挂载到 window，全局可访问");
        }
    }
}

#endif